package datastructure.array;

import lombok.ToString;

/**
 * 实现一个大小固定的有序数组，支持动态增删改操作
 *
 * @author hubb
 * @Date 2019/3/28 20:33
 */
@ToString
public class FixedArray {

    private int[] data;

    private int capacity;

    private int size;

    public FixedArray(int capacity) {
        this.data = new int[capacity];
        this.capacity = capacity;
        this.size = 0;
    }
    
    public void add(int e){
        this.data[size++]=e;
    }
    
    public void set(int index,int e){
        checkIndex(index);
        this.data[index] =e;
    }
    
    public void insert(int index,int e){
        checkIndex(index);
        for(int i=size-1;i>=index;i--){
            data[i+1]= data[i];
        }
        data[index] = e;
        size++;
    }
    
    public void delete(int index){
        checkIndexRang(index);
        for(int i=index+1;i<size;i++){
            data[i-1]= data[i];
        }
        size--;
        this.data[size]=0;
    }
    
    public int get(int index){
        checkIndexRang(index);
        return this.data[index];
    }
    
    private void checkIndex(int index){
        if(index<0||index>size){
            throw new IllegalArgumentException("下标错误,index必须大于等于0,或者小于等于size");
        }
    }

    private void checkIndexRang(int index){
        if(index<0||index>=size){
            throw new IllegalArgumentException("下标错误,index必须大于等于0,或者小于size");
        }
    }

}
